<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="format-detection" content="telephone=no" />
        <meta name="format-detection" content="email=no" />
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"
            name="viewport">
        <title>Simple Chatroom</title>
        <link rel="icon" href="">
    </head>
    <body style="text-align: center;">
        <div style="margin: 0 auto; width: 900px;">
            <div>
                <h1 style="font-size: 16px; line-height: 30px;">简易聊天室</h1>
            </div>
            <div style="text-align: left;">
                <div id="users">
                </div>
                <div id="message" style="height: 520px; overflow-y: auto; background-color: aliceblue;">
                </div>
                <div style="padding: 8px 0;">
                    <input type="text" maxlength="255" placeholder="请输入聊天内容，按Enter提交" id="content" style="width: 320px;">
                    <button type="button" id="btn-submit" disabled="disabled">提交</button>
                </div>
            </div>
        </div>
        <script src="https://cdn.bootcss.com/socket.io/2.0.4/socket.io.js"></script>
        <script src="./protobuf.min.js"></script>
        <script src="./client.js"></script>
        <script type="text/javascript">
            const room = "room_0";
            const randId = (10000 + parseInt(Math.random() * 1000000000) % 90000);
            const user = {
                userId: randId,
                name: "random #" + randId
            };
            
            const enableChat = function() {
                console.log("enjoy your chat time");
                document.getElementById('btn-submit').disabled = false;
            };
            const disableChat = function() {
                console.log("chat disabled. please refresh and try again.");
                document.getElementById('btn-submit').disabled = true;
            };
            
            // 连接 ws agent server 
            const agent = new Agent('ws://127.0.0.1:8888');
            // 可选 开启 pb3 支持
            agent.enablePb3('./protocol.js', ['ChatWords']);
            // 一些回调，请根据实际需要修改
            const doLogin = function() {
                agent.auth(user, function() {
                    agent.subscribeChannel(room, function() {
                        console.log(user.name + " has logined");
                        enableChat();
                    }, function() {
                        console.log("join room failed!");
                    });
                }, function() {
                    console.log("do login failed!");
                });
            };
            // 连接成功回调
            // 注意：重新连接 并连接成功时也会触发
            agent.onConnected(function() {
                console.log("connect callback...");
                doLogin();
            });
            // 尝试重新连接时的回调
            agent.onReconnect(function(attemptNumber) {
                console.log("reconnect callback... attempt #" + attemptNumber);
            });
            // 断开连接回调
            agent.onDisconnect(function(reason) {
                console.log("disconnect callback... reason: " + reason);
                disableChat();
            });
            
            // 设置推送消息的回调处理函数，请根据需要扩展
            agent.setMessageHandler("show", function(data) {
                // console.log(data);
                const content = "<p style=\"padding: 5px 10px; border-bottom: #ccc 1px dashed;\">" +
                                "  <em>" + (data.name === user.name ? "我" : data.name) + " : </em>" +
                                "  <span>" + data.words + "</span>" +
                                "</p>";
                const elem = document.createElement("div");
                elem.innerHTML = content;
                const $msg = document.getElementById("message");
                $msg.appendChild(elem);
                $msg.scrollTop = $msg.scrollHeight;
            });
            
            // 发送请求 应用实例
            const speak = function() {
                const words = document.getElementById("content").value;
                const param = {
                    room: room,
                    name: user.name,
                    words: words
                };
                document.getElementById("content").value = "";
                agent.query("speak", param);
                // 如果启用 pb3，使用下面方式编码 param，则整个 query 将自动编码为 pb3 Query 发送
                // agent.query("speak", Protocol.obj2pb3Data('ChatWords', param));
            };

            // start chat 
            document.getElementById("content").onkeydown = function(e) {
                e = e || event;
                if (e.keyCode === 13) {
                    speak();
                }
            };
            document.getElementById('btn-submit').onclick = function() {
                speak();
            };
        </script>
    </body>
</html>
